//
//  NewsViewController.m
//  WDFans
//
//  Created by Zhihong Yuan on 1/31/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "NewsViewController.h"
#import "ZHWebService.h"
#import "ZHDataService.h"
#import "MoreNewsViewController.h"
#import "ActivityViewManager.h"
#import "WDNews.h"
#import "UIImageView+LoadImagesFromInternet.h"
#import "DetailViewController.h"
#import "WDFansAppDelegate.h"



const NSInteger pageIndex = 1;
const NSInteger kShowNewsCount = 5;

@interface NewsViewController()
- (void)loadNewsViews;
@end

@implementation NewsViewController

@synthesize newsArray,nextPageExist;
@synthesize myScrollView,pageControl,noRecentNewsLabel;
@synthesize timer,moreView;
@synthesize detailControll;

#pragma mark - own methods
- (void)leftItemClicked
{
    //must be implemented in subclass
    self.myScrollView.contentOffset = CGPointMake(0, 0);
    self.navigationItem.rightBarButtonItem = nil;
    CompletionBlock completion = ^(NSData *data){
        
        
        if ([timer isValid]) {
            [timer invalidate];
        }
        [timer release];
        timer = nil;
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(autoScroll) userInfo:nil repeats:YES]; 
        
        NSDictionary *dict = [ZHDataService parseToNewesWithData:data];
        NSArray *news = [dict objectForKey:@"recentNews"];
        NSString *anyPage = [NSString stringWithFormat:@"%@",[dict objectForKey:@"page"]];
        
        // 没查到
        if([news count]==0)
            return;
        
        // 没更新
        if ([self.newsArray count]>0) {
            WDNews *n1 = [self.newsArray objectAtIndex:0];
            WDNews *n2 = [news objectAtIndex:0];
            if ([n1.newsTitle isEqualToString:n2.newsTitle]) {
                return;
            }
        }
        
        WDFansAppDelegate *appDelegate = (WDFansAppDelegate *)[UIApplication sharedApplication].delegate;
        NSArray* array = appDelegate.rootController.viewControllers;
        if ([array count]>0) {
            UINavigationController* vc = [array objectAtIndex:0];
            vc.tabBarItem.badgeValue = @"1";
        }
        
        
        
        self.newsArray = news;
        
        if([anyPage isEqualToString:@"0"])
            self.nextPageExist = NO;
        else
            self.nextPageExist = YES;
        [self loadNewsViews];
        self.noRecentNewsLabel.hidden = YES;
        
        
    };
    ErrorBlock error = ^(NSString *error){
        self.noRecentNewsLabel.hidden = NO;
    };
    [[ZHWebService sharedService] getRecentNewsWithPage:pageIndex onCompletion:completion onError:error];
}
- (void)rightItemClicked
{
    //must be implemented in subclass
    MoreNewsViewController *moreNewsController = [[MoreNewsViewController alloc] initWithFirstPageNews:self.newsArray andNextPage:self.nextPageExist];
    [self.navigationController pushViewController:moreNewsController animated:YES];
    [moreNewsController release];
}

- (void)loadNewsViews
{
    NSInteger newsCount;
    if([self.newsArray count] > kShowNewsCount)
        newsCount = kShowNewsCount;
    else
        newsCount = [self.newsArray count];
    self.pageControl.numberOfPages = newsCount;
    self.pageControl.currentPage = 0;
    for(UIView *v in [self.myScrollView subviews])
    {
        if([v isKindOfClass:[NewsShowView class]])
            [v removeFromSuperview];
    }
    CGFloat vWidth = self.myScrollView.frame.size.width;
    CGFloat vHeight = self.myScrollView.frame.size.height;
    for(int i = 0; i < newsCount; i++)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"NewsShowView" owner:self options:nil];
        NewsShowView *nv = (NewsShowView *)[nibs lastObject];
        nv.delegate = self;
        CGRect rect = nv.frame;
        rect.size.width = 320;
        rect.origin.x = i*vWidth; //+ kMarginLeft;
        rect.origin.y = 0; //kMarginTop;
        nv.frame = rect;
        [self.myScrollView addSubview:nv];
        //Fill data for news view
        WDNews *n = [self.newsArray objectAtIndex:i];
        nv.newsNameLabel.text = n.newsTitle;
        nv.newsDesLabel.text = n.newsDescription;
        nv.newsDesLabel.frame = [nv.newsDesLabel textRectForBounds:nv.newsDesLabel.frame limitedToNumberOfLines:0];
        NSString *date = nil;
        if(n.newsDate != nil)
        {
            NSArray *ta = [n.newsDate componentsSeparatedByString:@" "];
            date = [ta objectAtIndex:0];
        }
        nv.newsDateLabel.text = date;
        [nv.coverImageView loadImageAsynchronousWithURL:n.newsImageUrl placeHolderImage:kNameOfDefaultNewsImage];

        
    }
    [self.myScrollView setContentSize:CGSizeMake(vWidth*newsCount, vHeight)];

}

- (void)autoScroll
{
    if ([self.newsArray count]==0) {
        return;
    }
    
    CGFloat pageWidth = myScrollView.frame.size.width;
    NSInteger cp = floor((myScrollView.contentOffset.x - pageWidth/2)/pageWidth) + 1;
    
    cp += 1;

    self.pageControl.currentPage = cp % self.pageControl.numberOfPages;
    
    CGPoint p = myScrollView.contentOffset;
    
    if (self.pageControl.numberOfPages == self.pageControl.currentPage+1) {
//        [self addNaviBarRightItemWithTitle:@"更多"];
        
        if(self.moreView.frame.origin.y >321+46)
        {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDelegate:self];
            [UIView setAnimationDuration:0.3];
            self.moreView.frame = CGRectMake(0, 321+46, 320, 46);
            [UIView commitAnimations];
        }
    }
    else {
        self.navigationItem.rightBarButtonItem = nil;
        if(self.moreView.frame.origin.y == 321+46)
        {
            self.moreView.frame = CGRectMake(0, 321+46+46, 320, 46);
        }
    }
    
    // 最后一页
    if(self.pageControl.numberOfPages == self.pageControl.currentPage)
    {
        p.x = 0;
    }
    else {
        p.x = (self.myScrollView.contentSize.width/self.pageControl.numberOfPages)*self.pageControl.currentPage;
    }
    
    [myScrollView setContentOffset:p  animated:YES];
}

#pragma mark - View lifecycle
- (void)dealloc
{
    if ([timer isValid]) {
        [timer invalidate];
    }
    [timer release];
    timer = nil;
    
    detailControll.delegate = nil;
    [detailControll release];
    
    [moreView release];
    [noRecentNewsLabel release];
    [pageControl release];
    [myScrollView release];
    [newsArray release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewWillDisappear:(BOOL)animated
{
    if ([timer isValid]) {
        [timer invalidate];
    }
    [timer release];
    timer = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    
    if(self.moreView.frame.origin.y == 321+46)
    {
        self.moreView.frame = CGRectMake(0, 321+46+46, 320, 46);
    }
    
    self.pageControl.currentPage = 0;
    [self leftItemClicked];
    
    
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"新闻";
    [self setBackgroundImageViewForTabView];
    [self addNaviBarLeftRefreshItem];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.myScrollView = nil;
    self.pageControl = nil;
    self.noRecentNewsLabel = nil;
    self.moreView = nil;
}

#pragma -
#pragma UIScrollViewDelegate method
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pageWidth = scrollView.frame.size.width;
    NSInteger cp = floor((scrollView.contentOffset.x - pageWidth/2)/pageWidth) + 1;
    self.pageControl.currentPage = cp;
    
    if (self.pageControl.currentPage == self.pageControl.numberOfPages-1) {
        if(self.moreView.frame.origin.y >321+46)
        {
            [UIView beginAnimations:@"" context:nil];
            [UIView setAnimationDelegate:self];
            [UIView setAnimationDuration:0.3];
            self.moreView.frame = CGRectMake(0, 321+46, 320, 46);
            [UIView commitAnimations];
        }
    }
    else {
        if(self.moreView.frame.origin.y == 321+46)
        {
            self.moreView.frame = CGRectMake(0, 321+46+46, 320, 46);
        }
    }
    
    
    if([self.newsArray count] > kShowNewsCount)
    {
        if(cp == kShowNewsCount -1)
            [self addNaviBarRightItemWithTitle:@"更多"];
        else
            self.navigationItem.rightBarButtonItem = nil;
    }
    else
    {
        if(self.nextPageExist)
        {
            if(cp == [self.newsArray count]-1)
            {
                [self addNaviBarRightItemWithTitle:@"更多"];
            }
            else
                self.navigationItem.rightBarButtonItem = nil;
        }
    }
    
    if ([timer isValid]) {
        [timer invalidate];
    }
    [timer release];
    timer = nil;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(autoScroll) userInfo:nil repeats:YES]; 
}

#pragma mark - NewsShowViewDelegate methods
- (void)didShowNesDetail:(NewsShowView *)newsView
{
    
    CGRect rect = newsView.frame;
    NSInteger index = rect.origin.x/[[UIScreen mainScreen] bounds].size.width;

    WDNews *news = [self.newsArray objectAtIndex:index];
//    DetailViewController *detailControll = [[DetailViewController alloc] initWithNews:news];
    
    
    if (detailControll!=nil) {
        detailControll.delegate = nil;
        [detailControll release];
        detailControll = nil;
    }
    self.detailControll = [[Detail2ViewController alloc] initWithNews:news];
    detailControll.view.tag = 1;
    detailControll.delegate = self;
    
//    detailControll.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
//    [self presentModalViewController:detailControll animated:YES];
//    [self.navigationController pushViewController:detailControll animated:YES];
    
    WDFansAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
    
    [appDelegate.window addSubview:detailControll.view];
    
    detailControll.view.frame = CGRectMake(320, 20, 320, 460);
    detailControll.view.alpha = 0.3;
    
    [UIView beginAnimations:@"" context:nil];
    [UIView setAnimationDelegate:nil];
    [UIView setAnimationDuration:0.3];
    detailControll.view.frame = CGRectMake(0, 20, 320, 460);
    detailControll.view.alpha = 1.0;
    [UIView commitAnimations];
    
    if ([timer isValid]) {
        [timer invalidate];
    }
    [timer release];
    timer = nil;
    
//    [detailControll release];

    
    
    
    
}

#pragma mark - Detail2ViewControllerDelegate methods
-(void)removeView
{
    WDFansAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
    
    UIView* view = [appDelegate.window viewWithTag:1];
    [view removeFromSuperview];
    
    if ([timer isValid]) {
        [timer invalidate];
    }
    [timer release];
    timer = nil;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(autoScroll) userInfo:nil repeats:YES]; 
}


- (void)backClick
{
    WDFansAppDelegate* appDelegate = [[UIApplication sharedApplication] delegate];
    UIView* view = [appDelegate.window viewWithTag:1];
    
    [UIView beginAnimations:@"" context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDidStopSelector:@selector(removeView)];
    view.frame = CGRectMake(320, 20, 320, 460);
    view.alpha = 0.3;
    [UIView commitAnimations];
    
    
}






@end
